package kr.ac.konkuk.db.quadtree.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import kr.ac.konkuk.db.quadtree.RowKey;

import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

public class SampleParser {
	public static void parse(ParseHandler handler, InputStream is) {
		WKTReader wktReader = new WKTReader();
		BufferedReader reader;
		try {
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String line = null;
			while((line = reader.readLine()) != null) {
				Geometry geom = wktReader.read(line);
				handler.doProcess(geom);
			}
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void parse(ParseHandler handler, URL url) {
		InputStream is = null;
		try {
			is = url.openStream();
			parse(handler, is);
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			if (is != null) {
				try { is.close(); } catch(IOException e) {}
			}
		}
	}
	
	public static Map<RowKey, Geometry> toMap(URL url) {
		final Map<RowKey, Geometry> geometries = new TreeMap<RowKey, Geometry>();
		parse(new ParseHandler() {

			@Override
			public void doProcess(Geometry geom) {
				geometries.put(new RowKey(UUID.randomUUID().toString().getBytes()), geom);
			}
			
		}, url);
		
		return geometries;
	}
}
